package com.wanfajie.smsdistribute.ui.phone_group_content

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.OrientationHelper
import android.support.v7.widget.RecyclerView
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.wanfajie.smsdistribute.MyApplication
import com.wanfajie.smsdistribute.R
import com.wanfajie.smsdistribute.common.adapter.RecyclerViewHolder
import com.wanfajie.smsdistribute.db.bean.phone.PhoneNumber
import com.wanfajie.smsdistribute.db.quietInvoke
import com.wanfajie.smsdistribute.db.repository.impl.PlaceholderRepositoryImpl
import com.wanfajie.smsdistribute.util.toast
import kotlinx.android.synthetic.main.activity_person_detail.*
import java.sql.SQLException

class PhoneDetailActivity: AppCompatActivity() {

    companion object {
        val EXTRA_PHONE_ID = "phone_id"
        val EXTRA_KEY_ARRAY = "key_arr"

        private const val TAG = "PhoneDetailActivity"

        private val TAG_NAME = MyApplication.context.getString(R.string.person_name)
        private val TAG_TEL = MyApplication.context.getString(R.string.tel)

        fun startActivity(ctx: Context, number: PhoneNumber, keys: Array<String>? = null, requestCode: Int? = null) {
            val intent = Intent(ctx, PhoneDetailActivity::class.java)
            intent.putExtra(EXTRA_PHONE_ID, number.id)
            keys?.let {
                intent.putExtra(EXTRA_KEY_ARRAY, keys)
            }

            if (requestCode != null && ctx is Activity)
                ctx.startActivityForResult(intent, requestCode)
            else
                ctx.startActivity(intent)

        }
    }

    private lateinit var mKeyList: MutableList<String>
    private var mFieldValueMap: MutableMap<String, String> = HashMap()
    private lateinit var mNumber: PhoneNumber
    private val onItemClick: (View) -> Unit  = { it: View ->
        val index = it.tag as Int
        val key = mKeyList[index / 2]
        val value = mFieldValueMap[key] ?: ""

        EditDialog(this, mNumber.name, key) {
            val v = it.trim()

            when (key) {
                TAG_NAME -> {
                    mNumber.name = v
                    val succ = quietInvoke(TAG, false, SQLException::class) {
                        mNumber.update()
                        true
                    }
                    if (succ) {
                        toast(strId = R.string.successfully_modified)
                        mFieldValueMap[key] = v
                        title = v
                    } else {
                        toast(strId = R.string.modified_failure)
                    }
                }
                TAG_TEL -> if (mNumber.updateNumber(v)) {
                    toast(strId = R.string.successfully_modified)
                    mFieldValueMap[key] = v
                } else {
                    toast(getString(R.string.modified_failure_already_exists, it))
                }
                else -> {
                    mNumber.set(key, v)
                    mFieldValueMap[key] = v
                    toast(strId = R.string.successfully_modified)
                }
            }
            mAdapter.notifyItemRangeChanged(index, 2)
        }.setText(value)
                .show()
    }

    private val mAdapter by lazy {
        object : RecyclerView.Adapter<RecyclerViewHolder>() {
            override fun onCreateViewHolder(p0: ViewGroup, p1: Int): RecyclerViewHolder {
                val view = layoutInflater.inflate(R.layout.list_item_values, p0, false)
                view.setOnClickListener(onItemClick)
                return RecyclerViewHolder(view)
            }

            override fun getItemCount(): Int = mFieldValueMap.size * 2

            override fun onBindViewHolder(p0: RecyclerViewHolder, p1: Int) {
                val key = mKeyList[p1 / 2]
                p0.view as TextView
                if (p1 % 2 == 0) {
                    p0.view.text = key
                } else {
                    p0.view.text = mFieldValueMap[key]
                }

                p0.view.tag = p1
            }

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val id = intent.getIntExtra(EXTRA_PHONE_ID, -1)
        val phoneNumber = PhoneNumber.DAO.queryForId(id)
        if (phoneNumber == null) {
            finish()
            return
        }

        mKeyList = intent.getStringArrayExtra(EXTRA_KEY_ARRAY)?.toMutableList() ?:
            PlaceholderRepositoryImpl.queryNameByGroup(phoneNumber.group!!).toMutableList()

        mKeyList.add(0, TAG_TEL)
        mKeyList.add(0, TAG_NAME)

        mNumber = phoneNumber
        mKeyList.forEach {
            mFieldValueMap[it] = mNumber.get(it)
        }

        setContentView(R.layout.activity_person_detail)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        title = mNumber.name
        person_detail.layoutManager = GridLayoutManager(this, 5).apply {
            spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {

                override fun getSpanSize(p0: Int): Int {
                    return if (p0 % 2 == 0) 2 else 3
                }
            }
        }
        person_detail.addItemDecoration(DividerItemDecoration(this, OrientationHelper.VERTICAL))
        person_detail.addItemDecoration(DividerItemDecoration(this, OrientationHelper.HORIZONTAL))
        person_detail.adapter = mAdapter
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        return when (item?.itemId) {
            R.id.add -> {
                EditDialog(this, mNumber.name) {
                    val v = it.trim()
                    if (v.isEmpty()) {
                        toast(getString(R.string.cannot_be_empty, getString(R.string.tag_name)))
                        return@EditDialog
                    }

                    if (mFieldValueMap.containsKey(v)) {
                        toast(strId = R.string.failure_already_exists)
                    } else {
                        mNumber.set(v, "")
                        mFieldValueMap[v] = ""
                        mKeyList.add(v)
                        mAdapter.notifyItemRangeInserted((mKeyList.size - 1) * 2, 2)
                    }
                }.show()
                true
            }
            android.R.id.home -> {
                finish()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_tel_detail, menu)
        return true
    }
}